<template>
  <div
    :class="{ 'l-rblock': !['full', 'dialog','none'].includes(wraperType) }"
    style="overflow: hidden auto"
    v-loading="pageLoading"
    :element-loading-text="$t(pageLoadingText)"
  >
    <l-fullscreen-dialog
      v-if="wraperType == 'full'"
      :title="
        title || processTitle ?`${$t('发起流程')}【${title || processTitle}】${
          this.wfSecretLevel == 0 ? '【禁止上传涉秘信息】' : ''
        }`:`${$t('发起流程')}${
          this.wfSecretLevel == 0 ? '【禁止上传涉秘信息】' : ''
        }`
      "
      :visible.sync="midVisible"
      :showOk="false"
      :showClose="showClose"
      @closed="handleClosed"
      @opened="handleOpened"
      ref="formDialog"
    >
      <template #headerRight>
        <el-button-group style="margin-right: 8px">
          <el-button @click="handleCreateFlow" type="primary" size="mini"
            >{{$t('发起流程')}}</el-button
          >
        </el-button-group>
        <el-button-group style="margin-right: 8px">
          <el-button v-if="isDraftBtn" @click="handleSaveDraft" size="mini"
            >{{$t('保存草稿')}}</el-button
          >
        </el-button-group>

        <l-wordprint-btn
          style="margin-right: 8px"
          v-if="currentNode.formWrodPrintCode"
          :code="currentNode.formWrodPrintCode"
          :getFormData="getPrintData" 
        ></l-wordprint-btn>
      </template>

      <l-layout class="l-tab-page">
        <l-panel>
          <div class="l-auto-window" style="padding: 0 8px">
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
              <el-tab-pane v-if="hasWfForm" :label="$t('表单信息')" name="form">
                <div class="l-rblock" v-loading="formSchemeLoding">
                  <template v-if="showForm">
                    <l-form-viewer
                      v-if="formType == '1'"
                      :formInfo="formInfo"
                      :isWfForm="true"
                      :authFieldsMap="formAuthFieldsMap"
                      ref="wfForm"
                    ></l-form-viewer>
                    <component
                      ref="wfForm"
                      v-else
                      :requiredMap="formRequiredMap"
                      :authFieldsMap="formAuthFieldsMap"
                      :isWfForm="true"
                      :is="sysFormComponent"
                    ></component>
                  </template>
                </div>
              </el-tab-pane>
              <el-tab-pane :label="$t('流程信息')" name="wfinfo">
                <l-layout style="background: #f1f2f5">
                  <l-panel
                    class="flow-panel"
                    style="padding: 0; padding-top: 0"
                  >
                    <template #title>
                      <el-button-group>
                        <el-tooltip
                          effect="dark"
                          :content="$t('复原')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-aim"
                            @click="resetZoom"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          :content="$t('放大')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-zoom-in"
                            @click="handlerZoom(0.1)"
                          ></el-button>
                        </el-tooltip>
                        <el-tooltip
                          effect="dark"
                          :content="$t('缩小')"
                          placement="bottom"
                        >
                          <el-button
                            size="mini"
                            icon="el-icon-zoom-out"
                            @click="handlerZoom(-0.1)"
                          ></el-button>
                        </el-tooltip>
                      </el-button-group>
                    </template>
                    <b-wflow-viewer
                      ref="bflow"
                      isSimple
                      @elementClick="elementClick"
                    >
                    </b-wflow-viewer>
                  </l-panel>
                </l-layout>
              </el-tab-pane>
            </el-tabs>
          </div>
        </l-panel>
      </l-layout>
    </l-fullscreen-dialog>

    <l-dialog
      v-else-if="wraperType == 'dialog'"
      :title="
        `${$t(title)}${this.wfSecretLevel == 0 ? $t('【禁止上传涉秘信息】') : ''}`
      "
      :visible.sync="midVisible"
      :height="height"
      :width="width"
      @ok="handleCreateFlow"
      @close="handleClosed"
      @opened="handleOpened"
      ref="formDialog"
    >
      <template v-if="showForm">
        <l-form-viewer
          v-if="formType == '1'"
          :formInfo="formInfo"
          :isWfForm="true"
          :authFieldsMap="formAuthFieldsMap"
          ref="wfForm"
        ></l-form-viewer>
        <component
          ref="wfForm"
          v-else
          :requiredMap="formRequiredMap"
          :authFieldsMap="formAuthFieldsMap"
          :isWfForm="true"
          :is="sysFormComponent"
        ></component>
      </template>
      <template #btn>
        <l-wordprint-btn
          style="margin-right: 8px"
          v-if="currentNode.formWrodPrintCode"
          :code="currentNode.formWrodPrintCode"
          :getFormData="getPrintData" 
        ></l-wordprint-btn>
        <el-button v-if="isDraftBtn" @click="handleSaveDraft" size="mini"
          >{{$t('暂存')}}</el-button
        >

      </template>
    </l-dialog>

    <template v-else>
      <l-form-viewer
        v-if="formType == '1'"
        :formInfo="formInfo"
        :isWfForm="true"
        :authFieldsMap="formAuthFieldsMap"
        ref="wfForm"
      ></l-form-viewer>
      <component
        ref="wfForm"
        v-else
        :requiredMap="formRequiredMap"
        :authFieldsMap="formAuthFieldsMap"
        :isWfForm="true"
        :is="sysFormComponent"
      ></component>

      <template v-if="!wfNotShowWf">
        <div
          style="
            font-size: 14px;
            font-weight: bold;
            color: #333333;
            padding: 16px 8px;
          "
        >
          {{ $t("流程信息") }}
        </div>
        <div
          style="
            position: relative;
            width: 100%;
            min-height: 100px;
            padding: 8px;
            padding-top: 0;
          "
        >
          <div style="background: #f8f8f8">
            <b-wflow-viewer
              isSimple
              :isAutoHeight="false"
              ref="bflow"
              @elementClick="elementClick"
            />
          </div>
          <div
            class="l-rblock"
            style="position: absolute; top: 0; left: 0"
          ></div>
        </div>
        <div class="mt-8 mb-16 text-center">
          <el-button
            style="width: 200px"
            type="primary"
            @click="handleCreateFlow"
            :disabled="pageLoading"
            >{{ $t(wfSubmitText) }}</el-button
          >
        </div>
      </template>
    </template>

    <l-dialog
      :width="500"
      :height="nodeUsers.length * 48 + 88"
      :title="$t('选择下一审核节点人员')"
      :visible.sync="selectUsersVisible"
      @ok="handleSelectUsersSave"
      @close="handleSelectUsersCloseForm"
      :showClose="false"
    >
      <select-users ref="selectUsers" :nodeList="nodeUsers"></select-users>
    </l-dialog>

    <l-dialog
      :width="500"
      :height="320"
      :title="$t('填写流程信息')"
      :visible.sync="wfInfoVisible"
      @ok="handleSaveWfInfo"
      :showMinBtn="false"
      :showFullscreenBtn="false"
    >
      <div class="l-rblock pd-16">
        <el-form :model="formData" :rules="rules" size="mini" ref="form">
          <el-form-item :label="$t('流程标题')" prop="title" v-if="isCustmerTitle">
            <el-input v-model="formData.title" :placeholder="$t('请输入')" />
          </el-form-item>
          <el-form-item
            v-if="delegateUsers && delegateUsers.length > 0"
            :label="$t('流程发起人')"
            prop="userId"
          >
            <l-select
              valueKey="f_UserId"
              labelKey="f_RealName"
              :options="delegateUsers"
              v-model="formData.userId"
            />
          </el-form-item>
          <el-form-item
            v-if="appConfig.isSecretLevel"
            :label="$t('流程密级')"
            prop="secretLevel"
          >
            <l-secret-level-select
              v-model="formData.secretLevel"
              :maxSecretLevel="this.wfSecretLevel"
              :placeholder="$t('请选择')"
            />
          </el-form-item>
        </el-form>
      </div>
    </l-dialog>
  </div>
</template>

<script>
import mixin from "../../mixins/wf";
import SelectUsers from "../task/process/selectAuditUsers.vue";
import wfEvent from "../../util/event";

const api = window.$api.workflow.process;
const apiDelegate = window.$api.workflow.delegate;
export default {
  name: "wf-create-form",
  mixins: [mixin()],
  props: {
    isDraftBtn: {
      type: Boolean,
      default: true,
    },
    wraperType: {
      type: String,
      default: "full", // full 全屏,dialog 弹窗,page 页面，none 无页面
    },
    width: {
      type: Number,
      default: 800,
    },
    height: {
      type: Number,
      default: 600,
    },

    wfPrcessId: String,
    wfSubmitText: {
      type: String,
      default: "发起流程",
    },

    showClose: {
      type: Boolean,
      default: true,
    },

    wfNotShowWf: Boolean,
  },
  components: {
    SelectUsers,
  },
  data() {
    return {
      midVisible: false,
      isCustmerTitle: false,

      formData: {
        userId: "",
        title: "",
        secretLevel: 0,
      },
      rules: {
        title: [{ required: true, message: this.$t("请填写"), trigger: "blur" }],
        userId: [{ required: true, message: this.$t("请选择"), trigger: "blur" }],
        secretLevel: [{ required: true, message: this.$t("请选择"), trigger: "blur" }],
      },

      nodeUsers: [],
      selectUsersVisible: false,

      isDraft: false,

      pageLoading: false,
      pageLoadingText: "",

      wfViewerHieght: 100,

      wfInfoVisible: false,
    };
  },

  computed: {
    isNeedWfInfo() {
      return (
        this.isCustmerTitle ||
        (this.delegateUsers && this.delegateUsers.length > 0) ||
        this.appConfig.isSecretLevel
      );
    },
  },
  asyncComputed: {
    delegateUsers: {
      async get() {
        let code = this.code;
        if (!code && this.process) {
          code = this.process.f_SchemeCode;
        }

        if (code) {
          const data = await this.$awaitWraper(apiDelegate.getMyUserList(code));
          if (data && data.length > 0) {
            data.push(this.loginInfo);
          }
          return data || [];
        }
        return [];
      },
    },
  },
  watch: {
    visible: {
      handler(n) {
        this.midVisible = n;
      },
    },
  },
  async mounted() {
    if (this.wraperType == "page") {
      await this.handleOpened(this.showPgaeLoading, this.hidePageLoading);
      if (this.wfPrcessId) {
        this.processId = this.wfPrcessId;
      }
      this.$nextTick(() => {
        this.$refs.bflow &&
          this.$refs.bflow.setData(this.$deepClone(this.wfData), -0.3);
      });
    }
  },

  methods: {
    showPgaeLoading(text) {
      this.pageLoadingText = text || this.$t("保存数据中...");
      this.pageLoading = true;
    },
    hidePageLoading() {
      this.pageLoading = false;
    },
    showWFLoading(text) {
      if (this.$refs.formDialog) {
        this.$refs.formDialog.showLoading(text);
      } else {
        this.showPgaeLoading(text);
      }
    },
    hideWFLoading() {
      if (this.$refs.formDialog) {
        this.$refs.formDialog.hideLoading();
      } else {
        this.hidePageLoading();
      }
    },
    resetZoom() {
      this.$refs.bflow.reset();
    },
    handlerZoom(r) {
      this.$refs.bflow.handlerZoom(r);
    },

    elementClick() {},
    resetFormToMe() {
      this.isDraft = false;

      this.formData.userId = "";
      this.formData.title = "";
      this.formData.secretLevel = 0;
    },
    setForm() {
      this.formData.userId = this.loginInfo.f_UserId;
      this.currentNode = this.wfData.find((t) => t.type == "startEvent");
      this.isCustmerTitle = this.currentNode.isCustmerTitle;
      if (this.isCustmerTitle && this.type == "draft") {
        this.formData.title = this.process.f_Title;
      }
    },
    validateForm() {
      return this.$formValidateWraper(this.$refs.form);
    },
    async handleSaveDraft() {
      this.showWFLoading("保存草稿中...");
      if (!(await this.saveWfForm("draft"))) {
        this.hideWFLoading();
        return;
      }

      const wfData = {
        processId: this.processId,
        schemeCode: this.code,
        userId: this.formData.userId,
        title: this.formData.title,
        secretLevel: this.wfSecretLevel,
      };
      await api.saveDraft(wfData);

      this.isDraft = true;
      this.$message({
        type: "success",
        message: this.$t("保存成功!"),
      });

      await wfEvent.saveDraft(wfData);

      this.hideWFLoading();

      this.$emit("refresh");
    },

    async createWorkFlow(wfData) {
      wfData.secretLevel = this.formData.secretLevel;
      let res = await this.$awaitWraper(api.create(wfData));
      this.hideWFLoading();
      if(res){
        this.$message({
          type: "success",
          message: this.$t("创建成功!"),
        });
        await wfEvent.create(wfData);
        this.midVisible = false;
        this.$emit("refresh");
      }
    },
    async createDraftAndWorkFlow() {
      if (!(await this.saveWfForm("create"))) {
        this.hideWFLoading();
        return false;
      }
      // 创建流程
      const wfData = {
        processId: this.processId,
        schemeCode: this.isDraft ? "" : this.code,
        userId: this.formData.userId,
        title: this.formData.title,
        secretLevel: this.wfSecretLevel,
      };
      if (!this.isDraft) {
        await api.saveDraft(wfData);
        await wfEvent.saveDraft(wfData);
        wfData.schemeCode = "";
        this.isDraft = true;
      }
      // 获取接下来节点审核人
      if (this.currentNode.isNextAuditor) {
        const res = await api.getNextUsers({
          code: wfData.schemeCode,
          processId: this.processId,
          nodeId: this.currentNode.id,
        });
        const nodeUserMap = res.data.data;
        const nodeUsers = [];
        for (let key in nodeUserMap) {
          const nodeUserItem = nodeUserMap[key];
          if (nodeUserItem.length > 1) {
            nodeUsers.push({
              name: this.wfData.find((t) => t.id == key).name,
              id: key,
              options: nodeUserItem.map((t) => {
                return { value: t.id, label: t.name };
              }),
            });
          }
        }

        this.nodeUsers = nodeUsers;

        if (this.nodeUsers.length > 0) {
          this.selectUsersVisible = true;
          this.hideWFLoading();
          return false;
        }
      }

      await this.createWorkFlow(wfData);

      return true;
    },

    async handleCreateFlow(userId, processId) {
      if (processId && userId && typeof processId == 'string' && typeof userId == 'string') {
        this.isDraft = false;
        this.processId = processId;
        this.formData.userId = userId;
      }
      if(!this.formData.userId){
        this.formData.userId = this.loginInfo.f_UserId;
      }



      this.showWFLoading("创建流程...");

      if (!(await this.validateWfForm())) {
        this.hideWFLoading();
        return;
      }

      if (this.isNeedWfInfo) {
        this.wfInfoVisible = true;
        this.hideWFLoading();
        return;
      }

      await this.createDraftAndWorkFlow();
    },
    async handleSelectUsersSave() {
      this.selectUsersVisible = false;
      this.showWFLoading("创建流程...");

      // 创建流程
      const wfData = {
        processId: this.processId,
        schemeCode: this.isDraft ? "" : this.code,
        userId: this.formData.userId,
        title: this.formData.title,
        nextUsers: this.$refs.selectUsers.getForm(),
      };

      await this.createWorkFlow(wfData);
    },
    handleSelectUsersCloseForm() {
      this.$refs.selectUsers.resetForm();
    },

    // 流程的基本信息
    async handleSaveWfInfo() {
      this.showWFLoading("创建流程...");
      if (!(await this.validateForm())) {
        this.hideWFLoading();
        return;
      }
      this.wfInfoVisible = false;

      await this.createDraftAndWorkFlow();
    },
  },
};
</script>
